package com.example.tatil.service.impl;

import com.example.tatil.mapper.DeptMapper;
import com.example.tatil.mapper.EmpMapper;
import com.example.tatil.pojo.Dept;
import com.example.tatil.pojo.DeptLog;
import com.example.tatil.service.DeptLogService;
import com.example.tatil.service.DeptService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
@Transactional//spring事务管理 ,一旦出现异常会自动回滚
@Service
public class DeptServiceImpl implements DeptService {

//services不能直接对数据库进行操作注入mapper接口注解
    @Autowired
    private DeptMapper deptMapper;

    @Autowired
    private DeptLogService deptLogService;

    @Autowired
    private EmpMapper empMapper;
    @Override
    public List<Dept> list() {
        return  deptMapper.list();
    }

    @Transactional(rollbackFor = Exception.class)//所有的异常都会进行事务回滚

    @Override
    public void delete( Integer id) throws Exception {
        try {
            deptMapper.deleteById(id);
            int i  = 1/0;
//        if (true){
//            throw new Exception("出错了");
//        }
            empMapper.deleteByDeptId(id);


        } finally {
            DeptLog deptLog = new DeptLog();
            deptLog.setCreateTime(LocalDateTime.now());
            deptLog.setDescription("执行了解散部门的操作，此次解散的部门是"+id+"部门");
            deptLogService.insert(deptLog );
        }


    }

    @Override
    public void add(Dept dept) {
        dept.setCreateTime(LocalDateTime.now());
        dept.setUpdateTime(LocalDateTime.now());
        deptMapper.add(dept);
    }

    //根据id查询部门
    @Override
    public Dept select(Integer id) {
        Dept dept = deptMapper.selec(id);

        //利用mapper进行数据库操作
        return dept;

    }

//    根据id,name修改部门信息、
    @Override
    public void updateDept(Dept dept) {
        dept.setUpdateTime(LocalDateTime.now());
        deptMapper.updateDept(dept);


    }




}
